// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
  extends: require("./textureRenderUtils"),

  properties: {
    btn: {
      default: null, // The default value will be used only when the component attaching
      type: cc.Button, // optional, default is typeof default
    },
    pic: cc.Sprite,
  },
  onLoad() {
    this.touchId = null;
    this.pic.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.pic.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.pic.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
  },

  onTouchStart(e) {
    const param = this.getParam(e);
    this.paramStart = param;
    this.setPoint(param.x, param.y)
  },
  onTouchMove(e) {
    // console.log(e);
    const param = this.getParam(e);
    const { x, y, d, k } = param;
    this.pic.node.x -= this.paramStart.x - param.x;
    this.pic.node.y -= this.paramStart.y - param.y;

    if (d != 0 && this.paramStart.d != 0) {
      const s = this.pic.node.scale * (d / this.paramStart.d);
      this.pic.node.setScale(s);
    }
    if (k != 0 && this.paramStart.k != 0) {
      const r = this.pic.node.angle - ((this.paramStart.k - k) * 180) / Math.PI;
      this.pic.node.angle = r;
    }
    this.paramStart = param;
  },
  onTouchEnd(e) {
    // console.log(e);
    this.TouchStartMid = false
    // 防止两个手指同时抬起时的错差
    setTimeout(() => {
      this.touchId = null;
    }, 50);
  },
  getParam(e) {
    const touches = e.getTouches() || [];
    if (this.touchId === null) this.touchId = touches[0]._id;
    // let loc = e.getLocation();
    const loc = touches.filter((item) => item._id == this.touchId);
    // console.log(touches, this.touchId, loc);
    const { x, y } = loc.length ? loc[0]._point : this.paramStart;

    let d = 0;
    let k = 0;
    if (touches && touches.length > 1) {
      const { x: x1, y: y1 } = touches[0]._point;
      const { x: x2, y: y2 } = touches[1]._point;
      d = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
      k = Math.atan2(y2 - y1, x2 - x1);
      this.midpoint([x1, y1], [x2, y2])
    }
    return { x, y, d, k };
  },
  // 每次按下两个手指 => 设置注册点
  midpoint([x1, y1], [x2, y2]) {
    if (this.TouchStartMid) return
    this.TouchStartMid = true
    
    const [x, y] = [(x1 + x2) / 2, (y1 + y2) / 2]
    this.setPoint(x, y)
  },
  setPoint(x, y) {
    const { width, height, anchorX, anchorY } = this.pic.node;
    const loc = this.pic.node.convertToNodeSpaceAR(cc.v2(x, y))
    const aX = (loc.x + width * anchorX) / width;
    const aY = (loc.y + height * anchorY) / height;
    this.pic.node.x -= (anchorX - aX) * width
    this.pic.node.y -= (anchorY - aY) * height
    this.pic.node.setAnchorPoint(cc.v2(aX, aY))
    // console.log(loc.x, loc.y, aX, aY)
  },
  start() {
    const input = document.createElement("input");
    input.onchange = this.onUpdateFile.bind(this);
    input.setAttribute("id", "selFile"); //如没必要，可以不写
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*"); //不是选择图片的话，可以不写
    input.setAttribute("style", "display:none"); //不在页面显示
    document.body.appendChild(input);

    this.input = input;
  },
  // 点击事件
  onClickUpdate(e) {
    // console.log(e, cc);
    this.input.click();
  },
  onUpdateFile(e) {
    // console.log(e);
    const file = e.target.files[0];
    var reader = new FileReader();
    reader.onload = this.onReaderLoaded.bind(this);
    reader.readAsDataURL(file);
  },
  onReaderLoaded(e) {
    // console.log(e);
    var img = new Image();
    img.onload = this.onSetSprite.bind(this);
    img.src = e.target.result;
  },
  onSetSprite(e) {
    const base64Data = e.target || e.path[0];
    let imageObj = new Image();
    imageObj.src = base64Data.src;
    let textureObj = new cc.Texture2D();
    textureObj.initWithElement(imageObj);
    textureObj.handleLoadedTexture();
    this.pic.spriteFrame = new cc.SpriteFrame(textureObj);
    const { width: innerWidth, height: innerHeight } = cc.view.getVisibleSize();
    const { width, height } = imageObj;
    const [scaleX, scaleY] = [innerWidth / width, innerHeight / height];
    this.pic.node.setPosition(0, 0, 0);
    this.pic.node.setScale(scaleX < scaleY ? scaleX : scaleY);
    this.pic.node.angle = 0;
    this.pic.node.setAnchorPoint(cc.v2(0.5, 0.5))
    this.pic.node.setContentSize(width, height)

    console.log(cc.view.getVisibleSize(), imageObj.width, imageObj.height, scaleX < scaleY ? scaleX : scaleY)
  },

  // update (dt) {},
  onScreenShot() {
    this.init();
    this.createCanvas();
    var img = this.createImg();

    this.scheduleOnce(() => {
      // this.showImage(img);
      this.showImg(img);
      // download the pic as the file to your local
      this.label.string = "Showing the capture";
    }, 1);
  },
  showImg(img) {
    const div = document.createElement("div");
    const close = document.createElement("div");
    close.style =
      "width: 50px;\
    position: absolute;\
    height: 50px;\
    align-self: flex-start;";
    close.onclick = () => {
      div.remove();
    };
    div.style =
      "position: fixed;\
    width: 100%;\
    height: 100%;\
    display: flex;\
    justify-content: center;\
    align-items: center;\
    background: rgba(255,0,0,0.5);";
    div.appendChild(close);
    div.appendChild(img);
    img.style = "width:80%";
    document.body.appendChild(div);
  },
});
